<h2>Why is this an issue?</h2>
<p>One of the principles of a unit test is that it must have full control of the system under test. This is problematic when production code includes
calls to static methods, which cannot be changed or controlled. Date/time functions are usually provided by system libraries as static methods.</p>
<p>This can be improved by wrapping the system calls in an object or service that can be controlled inside the unit test.</p>
<h3>Noncompliant code example</h3>
<pre>
public class Foo
{
    public string HelloTime() =&gt;
        $"Hello at {DateTime.UtcNow}";
}
</pre>
<h3>Compliant solution</h3>
<p>There are different approaches to solve this problem. One of them is suggested below. There are also open source libraries (such as NodaTime) which
already implement an <code>IClock</code> interface and a <code>FakeClock</code> testing class.</p>
<pre>
public interface IClock
{
    DateTime UtcNow();
}

public class Foo
{
    public string HelloTime(IClock clock) =&gt;
        $"Hello at {clock.UtcNow()}";
}

public class FooTest
{
    public record TestClock(DateTime now) : IClock
    {
        public DateTime UtcNow() =&gt; now;
    }

    [Fact]
    public void HelloTime_Gives_CorrectTime()
    {
        var dateTime = new DateTime(2017, 06, 11);
        Assert.Equal((new Foo()).HelloTime(new TestClock(dateTime)), $"Hello at {dateTime}");
    }
}
</pre>
<p>Another possible solution is using an adaptable static class, ideally supports an IDisposable method, that not only adjusts the time behaviour for
the current thread only, but also for scope of the using.</p>
<pre>
public static class Clock
{
    public static DateTime UtcNow() { /* ... */ }
    public static IDisposable SetTimeForCurrentThread(Func&lt;DateTime&gt; time) { /* ... */ }
}

public class Foo
{
    public string HelloTime() =&gt;
        $"Hello at {Clock.UtcNow()}";
}

public class FooTest
{
    [Fact]
    public void HelloTime_Gives_CorrectTime()
    {
        var dateTime = new DateTime(2017, 06, 11);
        using (Clock.SetTimeForCurrentThread(() =&gt; dateTime))
        {
             Assert.Equal((new Foo()).HelloTime(), $"Hello at {dateTime}");
        }
    }
}
</pre>
<h2>Resources</h2>
<p><a href="https://nodatime.org/3.0.x/api/NodaTime.Testing.html">NodaTime testing</a></p>

